﻿function createButton(config, native) {
    var _btn;
    if (native) {
        _btn = $('<button>' + config.title + '</button>');
    }
    else {
        _btn = $('<div id="-add-confirm" class="x-button x-button-aawe"><span class="x-button-label">' + config.title + '</span></div>');
    }
    if (config.className) {
        _btn.addClass(config.className);
    }
    _btn.click(config.handler);
    return _btn;
}

function createInputDialog(config) {
    var _addPanel = $('<div id="-input-dialog-panel"></div>');
    $('body').append(_addPanel);

    var _container = $('<div id="-input-dialog"></div>');
    _addPanel.append(_container);

    if (config.title) {
        _container.append('<div class="-input-dialog-title">' + config.title + '</div>');
    }
    var _input = $('<input type="text" placeholder="' + config.placeholder + '" />');
    _container.append(_input);
    if (config.originalValue) {
        _input.val(config.originalValue);
    }
    _input.keydown(function (e) {
        if (e.key === 'Enter') {
            if (config.enter) {
                config.enter();
                e.preventDefault();
            }
        }
    });

    var _buttonContainer = $('<div class="-input-dialog-controls"></div>');
    _container.append(_buttonContainer);

    var _info;
    if (config.info) {
        _info = $('<span class="-input-dialog-info">' + config.info + '</span>');
    }
    else {
        _info = $('<span class="-input-dialog-info"></span>');
    }
    _buttonContainer.append(_info);

    setImmediate(function () {
        var _mainHeight = _container.height();
        _container.css('top', (window.innerHeight - _mainHeight) / 2);
        _container.css('opacity', 1);
    });

    var i, _button;
    for (i = config.buttons.length - 1; i >= 0; i--) {
        //_button = $('<div id="-add-confirm" class="x-button x-button-aawe"><span class="x-button-label">' + config.buttons[i].title + '</span></div>');
        //_button.click(config.buttons[i].handler);
        _buttonContainer.append(createButton(config.buttons[i], true));
    }

    _input.focus();

    var _dlg = {
        close: function () {
            $('body').css('height', '100%');
            _addPanel.remove();
        },
        getValue: function () {
            return _input.val();
        },
        focus: function () {
            _input.focus();
        },
        showInfo: function (info) {
            _info.text(info);
        },
        clear: function () {
            _input.val('');
            _input.focus();
        }
    };

    return _dlg;
}